package com.ruoyi.smartai.config;

import com.ruoyi.common.constant.CustomerPersonaAgents;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.smartai.service.IPersonaAgentsService;
import com.ruoyi.smartai.service.impl.DialogueServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.concurrent.CompletableFuture;

@Component
public class MorningMessageInitializer implements ApplicationListener<ApplicationReadyEvent> {

    private static final Logger log = LoggerFactory.getLogger(MorningMessageInitializer.class);
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IPersonaAgentsService personaAgentsService;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        log.info("应用启动完成，开始执行morning message初始化任务");

        // 异步执行，避免阻塞应用启动
        CompletableFuture.runAsync(this::processMorningMessages);
    }

    /**
     * 处理所有客服的morning message任务
     */
    private void processMorningMessages() {
        try {
            // 查询所有符合模式的键
            String keyPattern = "persona:customer:*:agents";
            Collection<String> keys = redisCache.keys(keyPattern);

            if (keys == null || keys.isEmpty()) {
                log.info("未找到符合模式'{}'的Redis键", keyPattern);
                return;
            }

            log.info("找到{}个符合模式的Redis键", keys.size());

            // 为每个键调用morningMessageJob方法
            for (String key : keys) {
                try {
                    // 从键中提取客服号码
//                    String customerNumber = extractCustomerNumber(key);
                    CustomerPersonaAgents agents = redisCache.getCacheObject(key);

                    if (agents != null && StringUtils.isNotNull(agents.getRestTime())) {
                        personaAgentsService.morningMessageJob(agents.getCustomerNumber(), agents.getRestTime());
                    } else {
                        log.warn("无法从键[{}]中提取客服号码", key);
                    }
                } catch (Exception e) {
                    log.error("处理键[{}]时发生错误", key, e);
                }
            }

            log.info("所有morning message任务已完成");
        } catch (Exception e) {
            log.error("执行Redis查询任务时发生错误", e);
        }
    }


}
